import woConfig from "./config.js"; // 本地配置数据
import Vue from 'vue'

var imgUrl = function (url) {
	var ret = /^http(s)?:\/\//;
	var retDataImage = /^data:image/;
	if (ret.test(url) || retDataImage.test(url)) {
		return url;
	} else {
		return woConfig.baseUrl + url;
	}
}

var buildRule = function (rule, title, errormsg) {
	var $u = Vue.prototype.$u
	
	var obj = {
		trigger: ['change', 'blur']
	}
	
	var ruleFun = new Map([
		['digits', () => {
			obj['type'] = 'number'
			obj.message = '请输入数字'
		}],
		['letters', () => {
			obj.validator = (rule, value, callback) => {
				if (rule.required && !value) {
					return false;
				}
				obj.message = '请输入字母'
				return $u.test.letter(value)
			}
		}],
		['date', () => {
			obj.message = '请输入正确的日期，格式:YYYY-MM-DD'
			obj.pattern = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
		}],
		['time', () => {
			obj.message = '请输入正确的时间，00:00到23:59之间'
			obj.pattern = /^([01]\d|2[0-3])(:[0-5]\d){1,2}$/;
		}],
		['email', () => {
			obj['type'] = 'email'
			obj.message = '请输入正确的邮箱'
		}],
		['url', () => {
			obj['type'] = 'url'
			obj.message = '请输入正确的URL'
		}],
		['qq', () => {
			// 最多11位，最小5位，不能以0开头
			obj.message = '请输入正确的QQ号码'
			obj.pattern = /^[1-9][0-9]{4,10}$/gim;
		}],
		['IDcard', () => {
			obj.validator = (rule, value, callback) => {
				if (rule.required && !value) {
					return false;
				}
				obj.message = '请输入正确的身份证号码'
				return $u.test.idCard(value)
			}
		}],
		['tel', () => {
			obj.message = '请输入正确的座机号码'
			obj.pattern = /^([0-9]{3,4}-)?[0-9]{7,8}/;
		}],
		['mobile', () => {
			obj.validator = (rule, value, callback) => {
				if (rule.required && !value) {
					return false;
				}
				obj.message = '请输入正确的手机号码'
				return $u.test.mobile(value)
			}
		}],
		['zipcode', () => {
			obj.message = '请输入正确的邮编'
			obj.pattern = /^[1-9]\d{5}$/g;
		}],
		['chinese', () => {
			obj.validator = (rule, value, callback) => {
				if (rule.required && !value) {
					return false;
				}
				obj.message = '请输入中文'
				return $u.test.chinese(value)
			}
		}],
		['username', () => {
			obj.message = '请填写3-12位数字、字母、下划线'
			obj.pattern = /^\w{3,12}$/;
		}],
		['password', () => {
			obj.message = '请填写6-16位字符，不能包含空格'
			obj.pattern = /^[\S]{6,16}$/;
		}],
		['default', () => {}]
	]);
	
	if (rule.includes('required')) {
		// 必填规则放到第一个，其他规则对它的 errormsg 进行覆盖
		obj['required'] = true
		obj.message = title + '不能为空'
	}
	for (let r in rule) {
		let action = ruleFun.get(rule[r]) || ruleFun.get('default')
		action.call(this, rule[r]);
	}
	obj.message = errormsg ? errormsg:obj.message
	return obj;
}

var buildUrl = function (type, token = false, data = null) {
	var buildFun = new Map([
		['suffix', () => {
			return woConfig.baseUrl +
				'/index/workorder/icon/suffix/' + data + '?token=' + token;
		}],
		['default', () => {
			console.log('default')
		}]
	]);
	
	let action = buildFun.get(type) || buildFun.get('default')
	return action.call(this);
}

export default {
	imgUrl,
	buildRule,
	buildUrl
}